package com.eylsun.demo;

import org.apache.commons.net.telnet.TelnetClient;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Pattern;

public class Main {

    public static void println(String msg) {
        System.out.println(msg);
    }

    public static void main(String[] args) {


        // write your code here
        try {
            println("****************************************\n" +
                    "**  Simple Check v0.1\n" +
                    "****************************************\n" +
                    "[e.g.]   simple-check.exe 127.0.0.1 5070");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            println("[Date]   " + sdf.format(new Date()));

            if (args.length != 2) {
                println("[simple-check]           INPUT ERROR!!");
                return;
            }
            println("[Host]   " + args[0]);
            println("[Port]   " + args[1]);

            Pattern p0 = Pattern.compile("^\\d+\\.\\d+\\.\\d+\\.\\d+$");
            Pattern p1 = Pattern.compile("^\\d+$");
            if (!p0.matcher(args[0]).find() || !p1.matcher(args[1]).find()) {
                println("[simple-check]           INPUT ERROR!!");
                return;
            }

            String host = args[0];
            int port = Integer.parseInt(args[1]);

            checkPing(host, port);
            checkTelnet(host, port);
            checkSip(host, port);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void checkPing(String host, int port) {
        try {
            int timeOut = 3000; //超时应该在3钞以上
            boolean status = InetAddress.getByName(host).isReachable(timeOut); // 当返回值是true时，说明host是可用的，false则不可。

            if (status)
                println("[simple-check]         ping:  OK");
            else
                println("[simple-check]         ping:  ERROR");
        } catch (Exception e) {
            println("[simple-check]         ping:  ERROR");
            e.printStackTrace();
        }

    }

    public static void checkTelnet(String host, int port) {
        try {
            TelnetClient telnet = new TelnetClient("vt200");
            telnet.setDefaultTimeout(3000);
            telnet.setConnectTimeout(3000);

            telnet.connect(host, port);
            telnet.disconnect();
            println("[simple-check]       telnet:  OK");

        } catch (SocketTimeoutException e) {
            println("[simple-check]       telnet:  TIMEOUT");
        } catch (ConnectException e) {
            println("[simple-check]       telnet:  ERROR");
        } catch (NoRouteToHostException e) {
            println("[simple-check]       telnet:  NoRouteToHost");
        } catch (Exception e) {
            println("[simple-check]       telnet:  ERROR");
            e.printStackTrace();
        }

    }


    public static void checkSip(String host, int port) {
        SocketAddress socketAddress = new InetSocketAddress(host, port);
        DatagramSocket datagramSocket;

        try {
            datagramSocket = new DatagramSocket();

            String uacUser = "35010100001320000000";
            String uacDomain = "3501010000";
            String uacIp = "127.0.0.1";
            int uacPort = datagramSocket.getLocalPort();
            String fromTag = UUID.randomUUID().toString();
            String callID = System.currentTimeMillis() + "";
            String branch = System.currentTimeMillis() + "";
            String uacAgent = "simple-gb28181";
            String uasUser = "34020000002000000001";
            String uasIp = host;
            String uasDomain = "3402000000";
            int uasPort = port;


            byte[] bt = ("REGISTER sip:" + uasUser + "@" + uasIp + " SIP/2.0\r\n" +
                    "Via: SIP/2.0/UDP " + uacIp + ":" + uacPort + ";rport;branch=" + branch + "\r\n" +
                    "Call-ID: REG_" + callID + "\r\n" +
                    "From: <sip:" + uacUser + "@" + uacDomain + ">;tag=" + fromTag + "\r\n" +
                    "To: <sip:" + uacUser + "@" + uacDomain + ">\r\n" +
                    "Contact: <sip:" + uacUser + "@" + uacIp + ":" + uacPort + ">\r\n" +
                    "CSeq: 1 REGISTER\r\n" +
                    "Max-Forwards: 70\r\n" +
                    "Expires: 10\r\n" +
                    "User-Agent: " + uacAgent + "\r\n" +
                    "Content-Length: 0\r\n" +
                    "\r\n").getBytes();

            byte[] buffer = new byte[1400];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, socketAddress);
            packet.setData(bt);
            datagramSocket.send(packet);

            datagramSocket.setSoTimeout(3000);
            datagramSocket.receive(packet);
            String receStr = new String(packet.getData(), 0, packet.getLength());
            boolean flag = receStr.contains("Call-ID: REG_" + callID);

            if (flag)
                println("[simple-check]     sip(udp):  OK");
            else {
                println("[simple-check]     sip(udp):  ERROR");
                println("receive=" + receStr);
            }


        } catch (SocketTimeoutException e) {
            println("[simple-check]     sip(udp):  TIMEOUT");
        } catch (Exception e) {
            println("[simple-check]     sip(udp):  ERROR");
            e.printStackTrace();
        }


    }


    public static void checkIp() {
        try {
            SocketAddress localSocket = new InetSocketAddress("10.16.234.72", 7050);

            InetAddress desIp = InetAddress.getByName("117.25.65.56");
            DatagramSocket ds = new DatagramSocket(localSocket);


            byte[] msg = "test".getBytes();
            DatagramPacket packet = new DatagramPacket(msg, msg.length, desIp, 7050);
            ds.send(packet);
            packet = new DatagramPacket(msg, msg.length, desIp, 7051);
            ds.send(packet);


            Socket socket = new Socket();
            socket.bind(localSocket);
            socket.connect(new InetSocketAddress("117.25.65.56", 7050));




        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
